package com.corpgovernment.common.requestprocess;

import java.util.StringJoiner;
import java.util.function.Consumer;
import java.util.function.Function;

import org.apache.commons.lang3.BooleanUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * @author dlz
 * @since 2023/9/20
 */
@Slf4j
public class LogUtils {
    private LogUtils() {}

    /**
     * 尝试执行某个方法并记录日志
     *
     * @param execFunc 要执行的方法
     * @param <R> 返回值类型
     * @return 执行结果
     */
    public static <R> R tryExecReturnLog(Function<StringJoiner, R> execFunc) {
        StringJoiner sj = new StringJoiner(System.lineSeparator());
        Exception e = null;
        try {
            return execFunc.apply(sj);
        } catch (Exception ex) {
            e = ex;
            throw ex;
        } finally {
            if (e != null) {
                log.error(sj.toString(), e);
            } else {
                log.info(sj.toString());
            }
        }
    }

    /**
     * 尝试执行某个方法并记录日志
     *
     * @param execFunc 要执行的方法
     */
    public static void tryExecVoidAndLog(Consumer<StringJoiner> execFunc) {
        // 换行
        StringJoiner sj = new StringJoiner(System.lineSeparator());
        Exception e = null;
        try {
            execFunc.accept(sj);
        } catch (Exception ex) {
            e = ex;
            throw ex;
        } finally {
            if (e != null) {
                log.error(sj.toString(), e);
            } else {
                log.info(sj.toString());
            }
        }
    }

    /**
     * 尝试执行一个日志任务，如果失败，会记录一条error级别的消息到log
     *
     * @param task 日志任务
     * @param errorMsg catch住异常时写入log的消息
     */
    public static void tryOrLogError(Runnable task, String errorMsg) {
        try {
            task.run();
        } catch (Exception e) {
            log.error(errorMsg, e);
        }
    }

    public static String boolToStr(Boolean b){
        return BooleanUtils.isTrue(b) ? "T" : "F";
    }
}
